<script lang="jsx">
import { defineComponent, unref } from 'vue'

export default defineComponent({
  name: 'TableColumn',
  props: {
    columns: {
      type: Array,
      default() {
        return []
      },
    },
  },
  setup(props, context) {
    const getSlots = (render, slotName, prop) => {
      const propName = slotName ?? prop
      const headerSlotName = (propName ?? prop) ? `${propName}-header` : ''
      const filterIconSlotName = propName ? `${propName}-filter-icon` : ''
      const expandSlotName = propName ? `${propName}-expand` : ''

      const slots = {
        // 具名插槽
        default: (scope) => {
          if (render) {
            return render(scope)
          }
          if (slotName) {
            return context.slots[slotName]?.(scope)
          }
          return scope.row[prop]
        },
        header: (scope) => {
          // 	自定义表头的内容，
          if (headerSlotName && !!context.slots[headerSlotName]) {
            return context.slots[headerSlotName](scope)
          }
        },
        'filter-icon': (scope) => {
          // 	自定义 filter 图标
          if (filterIconSlotName && !!context.slots[filterIconSlotName]) {
            return context.slots[filterIconSlotName](scope)
          }
        },
      }
      if (expandSlotName && !!context.slots[expandSlotName]) {
        slots.expand = (scope) => {
          return context.slots[expandSlotName](scope)
        }
      }
      return slots
    }

    const getColumn = (columns) => {
      return unref(columns).map((item) => {
        const { prop, label, render, hide, slotName, children, ...otherProp } = item
        if (hide === true) {
          return
        }

        const slots = getSlots(render, slotName, prop)

        return (
          <el-table-column {...otherProp} label={label} key={prop} v-slots={slots}>
            {children && getColumn(children)}
          </el-table-column>
        )
      })
    }
    return () => getColumn(props.columns)
  },
})
</script>

<style lang="scss" scoped></style>
